using System;
using System.Windows.Forms;
using MySqlConnector;

namespace Front._1124;

public partial class AddBookForm : Form
{
    public AddBookForm()
    {
        InitializeComponent();
        LoadCategories(); // 加载图书分类（从book_info提取）
        LoadPublishers(); // 加载出版社（关联publisher_info表）
        LoadShelves(); // 加载书架（关联shelf_info表）
    }

    // 加载图书分类（从book_info提取不重复分类）
    private void LoadCategories()
    {
        try
        {
            string connStr = "server=localhost;port=3306;database=book;user=root;password=root;charset=utf8mb4;AllowPublicKeyRetrieval=True;";
            using var connection = new MySqlConnection(connStr);
            connection.Open();

            string sql = "SELECT DISTINCT book_category FROM book_info ORDER BY book_category";
            using var command = new MySqlCommand(sql, connection);
            using var reader = command.ExecuteReader();

            while (reader.Read())
            {
                comboBoxCategory.Items.Add(reader.GetString("book_category"));
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show($"加载分类失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    // 加载出版社（关联publisher_info表）
    private void LoadPublishers()
    {
        try
        {
            string connStr = "server=localhost;port=3306;database=book;user=root;password=root;charset=utf8mb4;AllowPublicKeyRetrieval=True;";
            using var connection = new MySqlConnection(connStr);
            connection.Open();

            string sql = "SELECT publisher_id, publisher_name FROM publisher_info";
            using var command = new MySqlCommand(sql, connection);
            using var reader = command.ExecuteReader();

            while (reader.Read())
            {
                comboBoxPublisher.Items.Add(new
                {
                    Id = reader.GetInt32("publisher_id"),
                    Name = reader.GetString("publisher_name")
                });
            }

            comboBoxPublisher.DisplayMember = "Name";
            comboBoxPublisher.ValueMember = "Id";
        }
        catch (Exception ex)
        {
            MessageBox.Show($"加载出版社失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    // 加载书架（关联shelf_info表）
    private void LoadShelves()
    {
        try
        {
            string connStr = "server=localhost;port=3306;database=book;user=root;password=root;charset=utf8mb4;AllowPublicKeyRetrieval=True;";
            using var connection = new MySqlConnection(connStr);
            connection.Open();

            string sql = "SELECT shelf_id, shelf_code FROM shelf_info";
            using var command = new MySqlCommand(sql, connection);
            using var reader = command.ExecuteReader();

            while (reader.Read())
            {
                comboBoxShelf.Items.Add(new
                {
                    Id = reader.GetInt32("shelf_id"),
                    Code = reader.GetString("shelf_code")
                });
            }

            comboBoxShelf.DisplayMember = "Code";
            comboBoxShelf.ValueMember = "Id";
        }
        catch (Exception ex)
        {
            MessageBox.Show($"加载书架失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    // 保存按钮（适配book_info表所有必填字段）
    private void buttonSave_Click(object sender, EventArgs e)
    {
        // 校验必填项
        if (string.IsNullOrWhiteSpace(textBoxBookName.Text))
        {
            MessageBox.Show("请输入图书名称", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return;
        }
        if (comboBoxCategory.SelectedItem == null)
        {
            MessageBox.Show("请选择图书分类", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return;
        }
        if (comboBoxPublisher.SelectedItem == null)
        {
            MessageBox.Show("请选择出版社", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return;
        }
        if (comboBoxShelf.SelectedItem == null)
        {
            MessageBox.Show("请选择书架", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return;
        }
        if (!int.TryParse(textBoxPages.Text, out int pages) || pages <= 0)
        {
            MessageBox.Show("请输入有效的页数", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return;
        }
        if (!decimal.TryParse(textBoxPrice.Text, out decimal price) || price < 0)
        {
            MessageBox.Show("请输入有效的价格", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return;
        }

        try
        {
            string connStr = "server=localhost;port=3306;database=book;user=root;password=root;charset=utf8mb4;AllowPublicKeyRetrieval=True;";
            using var connection = new MySqlConnection(connStr);
            connection.Open();

            // 插入语句严格匹配book_info表字段
            string sql = @"INSERT INTO book_info (
                isbn, book_name, author, publisher_id, publish_date, 
                book_category, book_price, book_pages, book_desc, 
                book_status, shelf_id, purchase_date, book_version
            ) VALUES (
                @isbn, @bookName, @author, @publisherId, @publishDate, 
                @category, @price, @pages, @desc, 
                1, @shelfId, @purchaseDate, @version
            )";

            using var command = new MySqlCommand(sql, connection);
            // 绑定参数（严格对应表字段）
            command.Parameters.AddWithValue("@isbn", textBoxIsbn.Text.Trim());
            command.Parameters.AddWithValue("@bookName", textBoxBookName.Text.Trim());
            command.Parameters.AddWithValue("@author", textBoxAuthor.Text.Trim());
            command.Parameters.AddWithValue("@publisherId", ((dynamic)comboBoxPublisher.SelectedItem).Id);
            command.Parameters.AddWithValue("@publishDate", dateTimePickerPublishDate.Value);
            command.Parameters.AddWithValue("@category", comboBoxCategory.SelectedItem.ToString());
            command.Parameters.AddWithValue("@price", price);
            command.Parameters.AddWithValue("@pages", pages);
            command.Parameters.AddWithValue("@desc", textBoxDesc.Text.Trim());
            command.Parameters.AddWithValue("@shelfId", ((dynamic)comboBoxShelf.SelectedItem).Id);
            command.Parameters.AddWithValue("@purchaseDate", DateTime.Now.Date); // 采购日期默认为今天
            command.Parameters.AddWithValue("@version", textBoxVersion.Text.Trim());

            command.ExecuteNonQuery();
            MessageBox.Show("图书添加成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            this.DialogResult = DialogResult.OK;
            this.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show($"添加失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    // 取消按钮
    private void buttonCancel_Click(object sender, EventArgs e)
    {
        this.Close();
    }
}